/**
 * @description:
 * @author: 梅雄
 * @createDate: 2022/1/19
 * @version: 1.0
 * @status: done
 */
package com.xhwl.centiotdata.suppliersystem.eesd.hwweather;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xhwl.centiotdata.constant.EesdConstant;
import com.xhwl.centiotdata.pojo.dto.eesd.EesdConfigDTO;
import com.xhwl.centiotdata.utils.HttpUtils;
import com.xhwl.common.pojo.cent.bi.DwdFactEnvironmentMetrics;
import com.xhwl.common.utils.ChkUtil;
import com.xhwl.common.utils.DateUtils;
import com.xhwl.common.utils.MapsOf;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description:
 * @Copyright: Copyright (c) 2021  ALL RIGHTS RESERVED.
 * @Company: 深圳兴海物联科技有限公司
 * @Author: 梅雄
 * @CreateDate: 2022/1/19 9:27
 * @UpdateDate: 2022/1/19 9:27
 * @UpdateRemark: init
 * @Version: 1.0
 * @menu
 */
@Slf4j
@Component
class HwWeatherHandlerUtil {
    private static String aliApiHost;
    private static String aliApiConditionPath;
    private static String aliApiAirQualityPath;
    private static String aliAppcode;
    private static String conditionToken; //天气实况
    private static String airQualityToken; //空气质量
    @Value("${aliApi.host:null}")
    private String initAliApiHost;

    @Value("${aliApi.conditionPath:null}")
    private String initAliApiConditionPath;

    @Value("${aliApi.airQualityPath:null}")
    private String initAliAirQualityPath;

    @Value("${aliApi.appcode:null}")
    private String initAppcode;

    @Value("${aliApi.conditionToken:null}")
    private String initConditionToken;

    @Value("${aliApi.airQualityToken:null}")
    private String initAirQualityToken;

    @PostConstruct
    private void init(){
        HwWeatherHandlerUtil.aliApiHost = initAliApiHost;
        HwWeatherHandlerUtil.aliAppcode = initAppcode;
        HwWeatherHandlerUtil.aliApiConditionPath = initAliApiConditionPath;
        HwWeatherHandlerUtil.conditionToken = initConditionToken;
        HwWeatherHandlerUtil.aliApiAirQualityPath = initAliAirQualityPath;
        HwWeatherHandlerUtil.airQualityToken = initAirQualityToken;
    }

    /**
     * 获取结果集
     */
    static Map<String, Object> getRes(List<EesdConfigDTO> integrationConfig) {
        //缓存20分钟
        EesdConfigDTO eesdConfigDTO = integrationConfig.get(0);
        EesdConfigDTO.Weather weather = eesdConfigDTO.getWeather();
        //天气实况
        JSONObject wea = weather(weather, 1);
        //空气指数
        JSONObject env = weather(weather, 2);
        //处理参数
        String temp = ChkUtil.getString(wea.get("temp"));
        String humidity = ChkUtil.getString(wea.get("humidity"));
        Integer windLevel = ChkUtil.getInteger(wea.get("windLevel"));
        String pm25 = ChkUtil.getString(env.get("pm25"));
        Integer value = ChkUtil.getInteger(env.get("value"));
        String aqiVal = "";
        for (Map<String, Object> e : EesdConstant.aqi) {
            Integer begin = ChkUtil.getInteger(e.get("begin"));
            Integer end = ChkUtil.getInteger(e.get("end"));
            if (begin <= value && value <= end) {
                aqiVal = ChkUtil.getString(e.get("val"));
                break;
            }
        }
        return MapsOf.of(
                "projectId", eesdConfigDTO.getProjectId(),
                "obsTime", DateUtils.getCurrentDateTimeStandardStr(),
                "temp", temp,
                "humidity", humidity,
                "windScale", windLevel,
                "pm2p5", pm25,
                "category", value + "/" + aqiVal,
                "noise", "48"
        );
    }

    /**
     * 封装查询接口
     */
    private static JSONObject weather(EesdConfigDTO.Weather weather, int type) {
        String url;
        String token;
        if (type == 1) {
            url = aliApiConditionPath;
            token = conditionToken;
        } else {
            url = aliApiAirQualityPath;
            token = airQualityToken;
        }
        CloseableHttpClient client = null;
        try {
            Map<String, String> bodys = new HashMap<String, String>();
            bodys.put("lat", weather.getLat());
            bodys.put("lon", weather.getLon());
            bodys.put("token", token);
            Map<String, String> headers = new HashMap<String, String>();
            //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
            headers.put("Authorization", "APPCODE " + aliAppcode);
            //根据API的要求，定义相对应的Content-Type
            headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            Map<String, String> querys = new HashMap<String, String>();

            HttpResponse response = HttpUtils.doPost(aliApiHost,url,"POST",headers,querys,bodys);
            log.info("请求参数为：{}，请求结果为：{}",bodys.toString(),response.toString());
            HttpEntity resEntity = response.getEntity();
            if (resEntity != null) {
                String res = EntityUtils.toString(resEntity, "UTF-8");
                JSONObject jsonObject = JSON.parseObject(res);
                if ("0".equals(jsonObject.get("code") + "")) {
                    JSONObject data = jsonObject.getJSONObject("data");
                    if (type == 1) {
                        JSONObject condition = data.getJSONObject("condition");
                        jsonObject.put("key", "天气实况");
                        return condition;
                    } else {
                        JSONObject aqi = data.getJSONObject("aqi");
                        jsonObject.put("key", "空气指数");
                        return aqi;
                    }
                }
                throw new RuntimeException(res);
            } else {
                throw new RuntimeException("HttpEntity请求结构体是null");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (client != null) {
                    client.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return new JSONObject();
    }


    /**
     * 获取基本信息
     */
    static DwdFactEnvironmentMetrics getInfo(Integer projectId, String type, Double val) {
        DwdFactEnvironmentMetrics values = new DwdFactEnvironmentMetrics();
        values.setProjectId(projectId);
        values.setProductId(31);
        values.setGroupCode("室外");
        values.setName("阿里墨迹天气");
        values.setUpdateTime(LocalDateTime.now());
        values.setCreateTime(LocalDateTime.now());
        values.setType(type);
        if ("temp".equals(type)) {
            values.setTemp(val);
        } else if ("humidity".equals(type)) {
            values.setHumidity(val);
        } else if ("category".equals(type)) {
            values.setCategory(val + "");
        }else if ("windScale".equals(type)) {
            values.setWindScale(val + "");
        } else {
            values.setPm2p5(val);
        }
        return values;
    }
}
